package com.heima.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.admin.mapper.AdminLoginMapper;
import com.heima.admin.service.IAdminLoginService;
import com.heima.model.admin.dtos.AdUserDto;
import com.heima.model.admin.pojos.AdUser;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.utils.common.AppJwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
public class AdminLoginServiceImpl extends ServiceImpl<AdminLoginMapper,AdUser> implements IAdminLoginService {

    @Autowired
    private AdminLoginMapper adminLoginMapper;

    /**
     * 管理端用户登录
     * @param adUserDto
     * @return
     */
    @Override
    public ResponseResult login(AdUserDto adUserDto) {
        //校验用户名是否存在
        LambdaQueryWrapper<AdUser> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AdUser::getName, adUserDto.getName());
        AdUser adUser = adminLoginMapper.selectOne(queryWrapper);
        if (adUser == null) {
            log.info("用户名不存在");
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //校验密码是否正确
        String salt = adUser.getSalt();
        String password = adUserDto.getPassword();
        String md5DigestAsHex = DigestUtils.md5DigestAsHex((password + salt).getBytes());
        if (!adUser.getPassword().equals(md5DigestAsHex)) {
            log.info("密码错误：{}",md5DigestAsHex);
            return ResponseResult.errorResult(AppHttpCodeEnum.AP_USER_DATA_NOT_EXIST);
        }

        //处理敏感数据
        adUser.setSalt("");
        adUser.setPassword("");
        //封装并返回数据
        Map<String, Object> map = new HashMap<>();
        map.put("user", adUser);
        map.put("token", AppJwtUtil.getToken(adUser.getId().longValue(), adUser.getName()));

        ResponseResult result = new ResponseResult<>();
        result.setData(map);

        return result;
    }
}